package com.fosss.binarySearch;

/**
 * 非递归实现二分查找算法
 */
public class BinarySearch2 {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9, 55};
        int index = binarySearch(arr, 2);
        System.out.println(index);
    }

    private static int binarySearch(int[] arr,int value) {
        int left=0;
        int right=arr.length-1;
/*        int mid = (left + right) / 2;
        while (value<arr[mid]&&left<=right){
            //向左查找
            right=mid-1;
            mid=(left+right)/2;
        }
        while (value>arr[mid]&&left<=right){
            //向左查找
            left=mid+1;
            mid=(left+right)/2;
        }

        if(value==arr[mid]){
            return mid;
        }else {
            return -1;
        }*/

        //方法二
        while (left<=right){
            int mid = (left + right)/2;
            if(value<arr[mid]){
                right=mid-1;
            }else if(value> arr[mid]){
                left = mid+1;
            }else {
                return mid;
            }
        }
        return -1;
    }
}





